let express = require('express');
let router = express.Router();
let User = require("../model/UserInfo");
const {Op} = require("sequelize");

// 创建用户
router.post("/create", (req, res) => {
    //TODO 参数验证
    User.create({
        nickname: req.body.nickname,
        username: req.body.username,
        password: req.body.password,
        age: req.body.age,
    }).then((r) => {
        res.json({code: 200, message: "ok", data: r})
    });
});

//获取用户列表
router.get("/list", (req, res) => {

    // TODO 指定默认的分页参数
    User.findAll({
        offset: req.query.page,
        limit: req.query.size,
        order: [
            ['created_at', 'DESC']
        ]
    }).then((r) => {
        res.json({code: 200, message: "ok", data: r})
    })
});

//根据ID获取用户
router.get("/getOne/:id", (req, res) => {
    User.findByPk(req.params.id).then((r) => {
        res.json({code: 200, message: "ok", data: r})
    })
});

//搜索用户 （实现了根据用户昵称模糊搜索）
router.get("/search", (req, res) => {
    User.findAll({
        where: {
            nickname: {
                [Op.like]: "%" + req.query.nickname + "%"
            }
        }
    }).then((r) => {
        res.json({code: 200, message: "ok", data: r})
    })
})

router.post("/update/:id", (req, res) => {
    User.findByPk(req.params.id)
        .then((user) => {
            user.update({
                nickname: req.body.nickname,
                username: req.body.username,
                password: req.body.password,
                age: req.body.age
            }).then(r => {
                res.json({code: 200, message: "ok", data: r})
            })
        })
})

module.exports = router;
